package com.lft.stack;

public class LinkedListStack<T> {
	private Entry<T> headEntry;
	private int size = 0;
	
	public LinkedListStack() {
		headEntry = new Entry<>();
	}
	
	/**
	 * 入栈
	 * @param value
	 */
	public void push(T value) {
		Entry<T> newEntry = new Entry<>(value);
		newEntry.setNext(headEntry.getNext());
		headEntry.setNext(newEntry);
		size++;
	}
	
	/**
	 * 出栈
	 */
	public Entry<T> pop() {
		if (size < 1) {
			throw new RuntimeException("栈空，栈中没有数据");
		}
		Entry<T> temp = headEntry.getNext();
		headEntry.setNext(headEntry.getNext().getNext());
		size--;
		return temp;
	}
	
	/**
	 * 遍历
	 */
	public void lists() {
		if (isEmpty()) {
			System.out.println("栈空，栈中没有数据");
		}
		System.out.printf("栈中共有 %d 个元素。\n", size);
		Entry<T> temp = headEntry.getNext();
		for (int i = size; i > 0; i--) {
			System.out.println(temp);
			temp = temp.getNext();
		}
	}
	
	public boolean isEmpty() {
		return size == 0;
	}
	
	static class Entry<T> {
		private T value;
		private Entry<T> next;
		
		public Entry() {
			this(null);
		}
		
		public Entry(T value) {
			this.value = value;
			this.next = null;
		}
		
		public T getValue() {
			return value;
		}
		
		public void setValue(T value) {
			this.value = value;
		}
		
		public Entry<T> getNext() {
			return next;
		}
		
		public void setNext(Entry<T> next) {
			this.next = next;
		}
		
		@Override
		public String toString() {
			return "Entry{" +
					"value=" + value +
					'}';
		}
	}
}

